package com.zjz.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.要获取下载文件的路径
//        String realPath = this.getServletContext().getRealPath("/Servlet思维导图.png");  //F:\毕业设计\apache-tomcat-8.0.9\webapps\hello\Servlet思维导图.png
        String realPath = "F:\\AAA_Self_Study\\Java_webTest\\src\\main\\resources\\Servlet思维导图.png";
        System.out.println("下载文件的路径为：" + realPath);
        //2.下载的文件名
        String filename = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置想办法能够让浏览器支持（Content-Disposition）下载我们需要的东西
        resp.setHeader("Content-Disposition", "attachment;filename =  " + URLEncoder.encode(filename,"UTF-8"));
        //4.获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //5.创建缓存区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6.获取输出流OutputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //7.将FileOutputStream流写入buffer缓存区,使用OUtputStream将缓存区中的数据输出到客户端
        while((len = in.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }

        in.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
